import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import 'MarketItem.dart';

class MarketProvider with ChangeNotifier {
  final WebSocketChannel channel = WebSocketChannel.connect(
    Uri.parse('wss://example.com/market-data'), // 替换成你的 WebSocket 地址
  );

  Map<String, dynamic> marketData = {}; // 存储行情数据

  List<MarketItem> _items = [];

  List<MarketItem> get items => _items;

  MarketProvider() {
    _loadData();
    // listenToMarket();
  }

  void listenToMarket() {
    channel.stream.listen((data) {
      final parsedData = jsonDecode(data);
      marketData = parsedData; // 假设 API 返回的是 Map
      notifyListeners();
    });
  }

  @override
  void dispose() {
    channel.sink.close();
    super.dispose();
  }

  void _loadData() {
    _items = [
      MarketItem(
          name: "美元指数",
          code: "DXY",
          currentPrice: 107.922,
          change: -0.079,
          percentageChange: -0.07,
          buyPrice: 107.922,
          sellPrice: 107.923,
          yesterdayPrice: 108.00),
      MarketItem(
          name: "现货黄金",
          code: "USD",
          currentPrice: 2902.28,
          change: -2.13,
          percentageChange: -0.07,
          buyPrice: 2902.28,
          sellPrice: 2902.48,
          yesterdayPrice: 2904.4),
      MarketItem(
          name: "欧元/美元",
          code: "USD",
          currentPrice: 1.03946,
          change: 0.00116,
          percentageChange: 0.11,
          buyPrice: 1.03946,
          sellPrice: 1.03947,
          yesterdayPrice: 1.038),
    ];
    notifyListeners();
  }

// 更新价格
  void updateMarketItem(String code, double newPrice) {
    var item = _items.firstWhere((item) => item.code == code,
        orElse: () => MarketItem(
            name: "",
            code: "",
            currentPrice: 0,
            change: 0,
            percentageChange: 0,
            buyPrice: 0,
            sellPrice: 0,
            yesterdayPrice: 0));

    if (item.code.isNotEmpty) {
      item.updatePrice(newPrice);
      notifyListeners(); // 触发 UI 更新
    }
  }
}
